#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time      :2021/3/25 15:09
# @Author    :cjw
import requests
from time import sleep
from bs4 import BeautifulSoup


# 使用lxml解析器：pip install lxml

def get_pictures(page_nums=1):
	headers = {
		'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36'
	}
	for num in range(1, page_nums + 1):
		url = f'https://www.umei.cc/bizhitupian/weimeibizhi/{num}.htm'
		resp = requests.get(url, headers=headers)
		resp.encoding = 'utf-8'
		page_text = resp.text
		bs_page = BeautifulSoup(page_text, 'lxml')
		a_list = bs_page.find('div', attrs={'class': 'TypeList'}).find_all('a')
		href_list = [a.get('href') for a in a_list]
		print(len(href_list), href_list)
		for href in href_list:
			resp_href = requests.get(href, headers=headers)
			resp_href.encoding = 'utf-8'
			href_text = resp_href.text
			bs_href = BeautifulSoup(href_text, 'lxml')
			img = bs_href.find('div', attrs={'class': 'ImageBody'}).find('img')
			# 获取img标签的属性，使用get()方法
			alt, src = img.get('alt'), img.get('src')
			print(alt, src)
			img_resp = requests.get(src, headers=headers)
			with open(f'./image/{alt}.jpg', 'wb') as f:
				f.write(img_resp.content)
			img_resp.close()
			resp_href.close()
			sleep(0.3)
		resp.close()


if __name__ == '__main__':
	get_pictures(2)
